﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.SettingsPart
{
    public partial class ProjectsList : System.Web.UI.Page
    {
        private const string ProjectsDataSourceKey = "ProjectsDataSourceKey";
        private const string IsEditModeKey = "IsEditModeKey";
        private const string IsUpdateKey = "IsUpdateKey";

        public DataTable ProjectsListData
        {
            get
            {
                return ViewState[ProjectsDataSourceKey] != null
                           ? (DataTable)ViewState[ProjectsDataSourceKey]
                           : (DataTable)(ViewState[ProjectsDataSourceKey] = SiteMaster.Proxy.GetProjectsList());
            }

            set { ViewState[ProjectsDataSourceKey] = value; }
        }

        private bool IsAdmin
        {
            get
            {
                return Session[SiteMaster.IsAdminKey] != null && (bool)Session[SiteMaster.IsAdminKey];
            }
        }

        public bool IsEditMode
        {
            set { ViewState[IsEditModeKey] = value; }
            get { return ViewState[IsEditModeKey] != null && (bool) ViewState[IsEditModeKey]; }
        }

        public bool IsUpdate
        {
            set { ViewState[IsUpdateKey] = value; }
            get { return ViewState[IsUpdateKey] != null && (bool)ViewState[IsUpdateKey]; }
        }

        private int SelectedRow
        {
            get
            {
                int selectedRow;
                var isSuccessfully = int.TryParse(txtSelectedProject.Text, out selectedRow);

                if (isSuccessfully && selectedRow - 1 >= 0 && selectedRow - 1 < ProjectsListData.Rows.Count
                        && ProjectsListData.Rows[selectedRow - 1] != null)
                    return selectedRow - 1;

                return -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            if (IsEditMode)
            {
                txtProjectId.Enabled = false;

                if (!IsUpdate)
                {
                    txtProjectId.Text = txtProjectName.Text = "";
                }
                else
                {
                    var selectedRow = SelectedRow;

                    if (selectedRow == -1)
                        return;

                    txtProjectId.Text = ProjectsListData.Rows[selectedRow]["Id"].ToString();
                    txtProjectName.Text = ProjectsListData.Rows[selectedRow]["Name"].ToString();
                }
            }
            else
            {
                grdProjectsList.DataSource = ProjectsListData;
                grdProjectsList.DataBind();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            divEditMode.Visible = IsEditMode && IsAdmin;
            divProjectsGrid.Visible = !IsEditMode;

            btnAddProject.Visible = !IsEditMode;
            btnEditProject.Visible = btnRemoveProject.Visible = false;
            btnAddProject.Enabled = btnEditProject.Enabled = btnRemoveProject.Enabled = IsAdmin;

            grdProjectsList.Columns[1].Visible = IsAdmin;
            grdProjectsList.Columns[2].Visible = IsAdmin;

            btnBackToList.Visible = IsEditMode;
            btnBackToList.Enabled = IsAdmin;

            if (IsEditMode)
            {
                btnCreateUpdate.Text = IsUpdate ? "Update" : "Create";
            }

            Rebind();
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Add":
                    {
                        IsEditMode = true;
                        IsUpdate = false;

                        break;
                    }
                case "Remove":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedProject.Text = e.CommandArgument.ToString();

                        RemoveProject();

                        break;
                    }
                case "Edit":
                    {
                        IsEditMode = true;
                        IsUpdate = true;

                        break;
                    }

                case "Select":
                    {
                        txtSelectedProject.Text = e.CommandArgument.ToString();
                        IsEditMode = true;
                        IsUpdate = true;

                        break;
                    }

                case "SaveUpdate":
                    {
                        if (IsEditMode)
                        {
                            if (IsUpdate)
                            {
                                UpdateProject();
                            }
                            else
                            {
                                SaveProject();
                            }
                        }

                        break;
                    }

                case "BackToList":
                    {
                        IsEditMode = false;

                        break;
                    }
            }
        }

        private Dictionary<string, object> PrepareParameters(Dictionary<string, object> parameters)
        {
            parameters.Add("Name", txtProjectName.Text);

            return parameters;
        }

        private bool ValidateFields()
        {
            return Page.IsValid;
        }

        private void SaveProject()
        {
            if (!ValidateFields())
                return;

            var parameters = PrepareParameters(new Dictionary<string, object>());

            SiteMaster.Proxy.CreateProject(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            ProjectsListData = null;
        }

        private void UpdateProject()
        {
            if (!ValidateFields())
                return;

            var parameters = new Dictionary<string, object>();

            int intParseValue;
            var isParsed = int.TryParse(txtProjectId.Text, out intParseValue);

            if (!isParsed)
                return;

            parameters.Add("Id", intParseValue);

            parameters = PrepareParameters(parameters);

            SiteMaster.Proxy.UpdateProject(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            ProjectsListData = null;
        }

        private void RemoveProject()
        {
            var selectedRow = SelectedRow;

            if (selectedRow == -1)
                return;

            int intParseValue;
            var isParsed = int.TryParse(ProjectsListData.Rows[selectedRow]["Id"].ToString(), out intParseValue);

            if (!isParsed)
                return;

            SiteMaster.Proxy.RemoveProject(intParseValue, Page.User.Identity.Name);

            IsEditMode = false;
            ProjectsListData = null;
        }
    }
}